package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.UserAddressBookMappper;
import com.sky.service.UserAddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserAddressBookServiceImpl implements UserAddressBookService {

    @Autowired
    private UserAddressBookMappper userAddressBookMappper;

    @Override
    public AddressBook defaultAddressBook() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        return userAddressBookMappper.defaultAddressBook(addressBook);
    }

    @Override
    public void updateDefaultAddressBook(AddressBook addressBook) {
        if(Objects.equals(addressBook.getId(), defaultAddressBook().getId())){

            return;
        }


        //把之前的默认地址改成0
        AddressBook oldDefaultAddress = defaultAddressBook();
        oldDefaultAddress.setIsDefault(0);
        userAddressBookMappper.updateDefaultStatus(oldDefaultAddress);
        //把传递来的地址改为1
        AddressBook newDefaultAddress = userAddressBookMappper.getById(addressBook.getId());
        newDefaultAddress.setIsDefault(1);
        userAddressBookMappper.updateDefaultStatus(newDefaultAddress);
    }

    @Override
    public List list() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = userAddressBookMappper.list(addressBook);
        return list;
    }

    @Override
    public AddressBook getById(Integer id) {
        return userAddressBookMappper.getById(Long.valueOf(id));
    }

    @Override
    public void deleteById(Integer id) {
        userAddressBookMappper.deleteById(id);
    }

    @Override
    public void
    update(AddressBook addressBook) {
        userAddressBookMappper.update(addressBook);
    }

    @Override
    public void save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        if(addressBook.getIsDefault()==null){
            addressBook.setIsDefault(1);
        }
        userAddressBookMappper.insert(addressBook);
    }
}
